package com.cinema.service;

import com.cinema.dao.UserDao;
import com.cinema.dao.impl.UserDaoImpl;
import com.cinema.model.User;
import com.cinema.model.UserType;
import com.cinema.util.LogUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务类
 * 提供用户管理的业务逻辑
 */
public class UserService {
    
    private final UserDao userDao;
    private User currentUser; // 当前登录用户
    
    public UserService() {
        this.userDao = new UserDaoImpl();
    }
    
    /**
     * 用户登录
     */
    public boolean login(String username, String password) {
        try {
            User user = userDao.validateLogin(username, password);
            if (user != null) {
                this.currentUser = user;
                LogUtil.logLogin(username, user.getUserType().getDescription(), true);
                return true;
            } else {
                LogUtil.logLogin(username, "未知", false);
                return false;
            }
        } catch (Exception e) {
            LogUtil.logError("用户登录", "登录过程发生错误: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 用户登出
     */
    public void logout() {
        if (currentUser != null) {
            LogUtil.logLogout(currentUser.getUsername(), currentUser.getUserType().getDescription());
            this.currentUser = null;
        }
    }
    
    /**
     * 获取当前登录用户
     */
    public User getCurrentUser() {
        return currentUser;
    }
    
    /**
     * 检查是否已登录
     */
    public boolean isLoggedIn() {
        return currentUser != null;
    }
    
    /**
     * 检查当前用户是否需要修改密码
     */
    public boolean needPasswordChange() {
        return currentUser != null && currentUser.isNeedPasswordChange();
    }
    
    /**
     * 修改当前用户密码
     */
    public boolean changeCurrentUserPassword(String oldPassword, String newPassword) {
        if (currentUser == null) {
            return false;
        }
        
        if (!currentUser.getPassword().equals(oldPassword)) {
            LogUtil.logError("密码修改", "原密码错误");
            return false;
        }
        
        boolean success = userDao.changePassword(currentUser.getUserId(), newPassword);
        if (success) {
            currentUser.setPassword(newPassword);
            currentUser.setNeedPasswordChange(false);
            LogUtil.logPasswordChange(currentUser.getUsername(), currentUser.getUsername(), true);
        }
        return success;
    }
    
    /**
     * 强制修改密码（首次登录或重置后）
     */
    public boolean forceChangePassword(String newPassword) {
        if (currentUser == null) {
            return false;
        }
        
        boolean success = userDao.changePassword(currentUser.getUserId(), newPassword);
        if (success) {
            currentUser.setPassword(newPassword);
            currentUser.setNeedPasswordChange(false);
            LogUtil.logPasswordChange(currentUser.getUsername(), currentUser.getUsername(), true);
        }
        return success;
    }
    
    /**
     * 重置用户密码（管理员/经理功能）
     */
    public boolean resetUserPassword(String targetUserId) {
        if (currentUser == null) {
            return false;
        }
        
        // 权限检查
        if (!canResetPassword(targetUserId)) {
            LogUtil.logError("密码重置", "权限不足，无法重置密码");
            return false;
        }
        
        User targetUser = userDao.findById(targetUserId);
        if (targetUser == null) {
            LogUtil.logError("密码重置", "目标用户不存在");
            return false;
        }
        
        boolean success = userDao.resetPassword(targetUserId);
        if (success) {
            LogUtil.logPasswordChange(currentUser.getUsername(), targetUser.getUsername(), false);
        }
        return success;
    }
    
    /**
     * 检查是否有权限重置密码
     */
    private boolean canResetPassword(String targetUserId) {
        if (currentUser == null) {
            return false;
        }
        
        User targetUser = userDao.findById(targetUserId);
        if (targetUser == null) {
            return false;
        }
        
        // 管理员可以重置经理和用户的密码
        if (currentUser.getUserType() == UserType.ADMIN) {
            return targetUser.getUserType() != UserType.ADMIN || 
                   !targetUser.getUsername().equals("admin"); // 不能重置admin账户
        }
        
        // 经理只能重置用户的密码
        if (currentUser.getUserType() == UserType.MANAGER) {
            return targetUser.getUserType() == UserType.USER;
        }
        
        return false;
    }
    
    /**
     * 添加用户（管理员功能）
     */
    public boolean addUser(String username, String phoneNumber, UserType userType) {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            LogUtil.logError("用户添加", "权限不足");
            return false;
        }
        
        // 创建新用户
        User newUser = new User();
        newUser.setUserId(((UserDaoImpl) userDao).getNextUserId());
        newUser.setUsername(username);
        newUser.setPassword("123456"); // 默认密码
        newUser.setPhoneNumber(phoneNumber);
        newUser.setUserType(userType);
        newUser.setRegistrationTime(LocalDateTime.now());
        newUser.setNeedPasswordChange(true);
        
        boolean success = userDao.save(newUser);
        if (success) {
            LogUtil.logUserManagement(currentUser.getUsername(), "添加", 
                    username, userType.getDescription());
        }
        return success;
    }
    
    /**
     * 删除用户（管理员功能）
     */
    public boolean deleteUser(String userId) {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            LogUtil.logError("用户删除", "权限不足");
            return false;
        }
        
        User targetUser = userDao.findById(userId);
        if (targetUser == null) {
            LogUtil.logError("用户删除", "用户不存在");
            return false;
        }
        
        // 不能删除admin账户
        if ("admin".equals(targetUser.getUsername())) {
            LogUtil.logError("用户删除", "不能删除admin管理员账户");
            return false;
        }
        
        boolean success = userDao.delete(userId);
        if (success) {
            LogUtil.logUserManagement(currentUser.getUsername(), "删除", 
                    targetUser.getUsername(), targetUser.getUserType().getDescription());
        }
        return success;
    }
    
    /**
     * 更新用户信息（管理员功能）
     */
    public boolean updateUser(String userId, String phoneNumber, UserType userType) {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            LogUtil.logError("用户更新", "权限不足");
            return false;
        }
        
        User user = userDao.findById(userId);
        if (user == null) {
            LogUtil.logError("用户更新", "用户不存在");
            return false;
        }
        
        // 更新信息
        user.setPhoneNumber(phoneNumber);
        user.setUserType(userType);
        
        boolean success = userDao.update(user);
        if (success) {
            LogUtil.logUserManagement(currentUser.getUsername(), "修改", 
                    user.getUsername(), userType.getDescription());
        }
        return success;
    }
    
    /**
     * 根据ID查找用户
     */
    public User findUserById(String userId) {
        return userDao.findById(userId);
    }
    
    /**
     * 根据用户名查找用户
     */
    public User findUserByUsername(String username) {
        return userDao.findByUsername(username);
    }
    
    /**
     * 获取所有用户列表（管理员功能）
     */
    public List<User> getAllUsers() {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            return null;
        }
        return userDao.findAll();
    }
    
    /**
     * 根据用户类型获取用户列表
     */
    public List<User> getUsersByType(UserType userType) {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            return null;
        }
        return userDao.findByUserType(userType);
    }
    
    /**
     * 搜索用户（根据ID或用户名）
     */
    public List<User> searchUsers(String keyword) {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            return null;
        }
        
        List<User> allUsers = userDao.findAll();
        return allUsers.stream()
                .filter(user -> user.getUserId().toLowerCase().contains(keyword.toLowerCase()) ||
                               user.getUsername().toLowerCase().contains(keyword.toLowerCase()) ||
                               user.getPhoneNumber().contains(keyword))
                .collect(Collectors.toList());
    }
    
    /**
     * 格式化用户信息显示
     */
    public String formatUserInfo(User user) {
        if (user == null) {
            return "用户信息为空";
        }
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return String.format("用户ID: %s | 用户名: %s | 用户类型: %s | 手机号: %s | 注册时间: %s | 需修改密码: %s",
                user.getUserId(),
                user.getUsername(),
                user.getUserType().getDescription(),
                user.getPhoneNumber(),
                user.getRegistrationTime().format(formatter),
                user.isNeedPasswordChange() ? "是" : "否");
    }
    
    /**
     * 获取用户统计信息
     */
    public String getUserStatistics() {
        if (currentUser == null || currentUser.getUserType() != UserType.ADMIN) {
            return "权限不足";
        }
        
        int totalUsers = userDao.getUserCount();
        int adminCount = userDao.getUserCountByType(UserType.ADMIN);
        int managerCount = userDao.getUserCountByType(UserType.MANAGER);
        int userCount = userDao.getUserCountByType(UserType.USER);
        
        return String.format("用户统计信息：\n总用户数: %d\n管理员: %d人\n经理: %d人\n用户: %d人",
                totalUsers, adminCount, managerCount, userCount);
    }
    
    /**
     * 验证用户名格式
     */
    public boolean isValidUsername(String username) {
        return username != null && username.matches("^[a-zA-Z0-9_]{3,20}$");
    }
    
    /**
     * 验证手机号格式
     */
    public boolean isValidPhoneNumber(String phoneNumber) {
        return phoneNumber != null && phoneNumber.matches("^1[3-9]\\d{9}$");
    }
    
    /**
     * 检查用户名是否已存在
     */
    public boolean isUsernameExists(String username) {
        return userDao.existsByUsername(username);
    }
    
    /**
     * 检查手机号是否已存在
     */
    public boolean isPhoneNumberExists(String phoneNumber) {
        return userDao.existsByPhoneNumber(phoneNumber);
    }
    
    /**
     * 修改密码（通用方法）
     */
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            LogUtil.logError("密码修改", "用户不存在");
            return false;
        }
        
        if (!user.getPassword().equals(oldPassword)) {
            LogUtil.logError("密码修改", "原密码错误");
            return false;
        }
        
        boolean success = userDao.changePassword(user.getUserId(), newPassword);
        if (success) {
            LogUtil.logPasswordChange(currentUser != null ? currentUser.getUsername() : "系统", 
                    username, true);
        }
        return success;
    }
    
    /**
     * 重置密码（通过用户名）
     */
    public boolean resetPassword(String operatorUsername, String targetUsername) {
        if (currentUser == null) {
            return false;
        }
        
        User targetUser = userDao.findByUsername(targetUsername);
        if (targetUser == null) {
            LogUtil.logError("密码重置", "目标用户不存在");
            return false;
        }
        
        // 权限检查
        if (!canResetPassword(targetUser.getUserId())) {
            LogUtil.logError("密码重置", "权限不足，无法重置密码");
            return false;
        }
        
        boolean success = userDao.resetPassword(targetUser.getUserId());
        if (success) {
            LogUtil.logPasswordChange(operatorUsername, targetUsername, false);
        }
        return success;
    }
    
    /**
     * 获取所有普通用户
     */
    public List<User> getAllNormalUsers() {
        return userDao.findByUserType(UserType.USER);
    }
}